<?php
class Core_Model_Table_Storage extends Database_Table
{
	protected $_name = 'core_storages';

	/**
	 * get default storage service id
	 * @return int
	 */
	public function getDefaultId()
	{
		$select = $this -> select() -> where('is_active=1') -> where('is_default=1') -> order('sort_order');
		$row = $this -> fetchRow($select);

		if (is_object($row))
		{
			return $row -> getId();
		}

		$select = $this -> select() -> where('is_active=1') -> order('sort_order');
		$row = $this -> fetchRow($select);

		if (is_object($row))
		{
			$row -> is_default = 1;
			$row -> description = 'this service is set to default because there are no default service to storage!';
			return $row -> getId();
		}

		$select = $this -> select() -> where('service_id=?', 'local') -> order('sort_order');

		if (is_object($row))
		{
			$row -> is_default = 1;
			$row -> is_active = 1;
			$row -> description = 'this service is set to default because there are no default service to storage!';
			return $row -> getId();
		}

		throw new Agilet_Exception('There are no active storage sevice!');
	}

	public function get($id)
	{
		$key = 'core/storage/service/' . $id;
		
		if (false == ($data = Cache::instance() -> get($key)))
		{
			$row = $this -> find(intval($id)) -> current();

			if (!is_object($row))
			{
				throw new Agilet_Exception('there are no service id {$id}', array('{$id}' => $id));
			}

			$data = unserialize($row -> serialized_data);

			if (null == $data)
			{
				throw new Agilet_Exception('Service id {$id} still have not configured!', array('{$id}' => $id));
			}

			Cache::instance() -> set($key, $data);
		}

		return $data;
	}

	public function set($id, $data)
	{
		$row = $this -> find(intval($id)) -> current();

		if (!is_object($row))
		{
			throw new Agilet_Exception('there are no service id {$id}', array('{$id}' => $id));
		}

		foreach (array('title','description','is_active','is_locked','updated_at','is_default') as $dirty)
		{
			if (isset($data[$dirty]))
			{
				unset($data[$dirty]);
			}
		}
		
		$row -> serialized_data = serialize($data);

		$row -> save();
		
		$key = 'core/storage/service/' . $id;
		
		Cache::instance() -> remove($key);
	}

}
